import axios, { AxiosInstance, AxiosResponse, AxiosError, AxiosRequestConfig } from 'axios'
import router from '@/router/index'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

nprogress.configure({ showSpinner: false })

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_API,
  timeout: 8000
})

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    (window as any).showGlobalLoading()
    if (sessionStorage.token) {
      const headers: any = config.headers
      headers.Authorization = sessionStorage.token
    }
    nprogress.start()
    return config
  }, (error: AxiosError) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use((response: AxiosResponse) => {
  (window as any).hideGlobalLoading()
  const res = response.data
  nprogress.done()
  if (response.status === 200) {
    // 无感重新发起请求
    if (res.code == '00006' || (res.message && res.message.includes('登录'))) {
      sessionStorage.removeItem('authorization')
      // 重新发起请求
      return service.request(response.config)
    } 
    return validToken(response)
  } else {
    return Promise.reject()
  }
}, (error: AxiosError) => {
  return Promise.reject(error)
}
)

function validToken(response: AxiosResponse) {
  const code = ['201', '404', '500']
  if (code.includes(response?.data?.code)) {
    sessionStorage.removeItem('token')
    router.replace('/404')
    setTimeout(() => {
      router.replace('/login')
    }, 5000)
    return Promise.reject()
  } else {
    return response.data
  }
}

export default service